package com.wlbx.agent.ui.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.fingerprint.FingerprintManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;

import android.os.Handler;
import android.os.Message;
import android.security.keystore.KeyProperties;
import android.view.Gravity;
import androidx.core.hardware.fingerprint.FingerprintManagerCompat;
import androidx.core.os.CancellationSignal;
import androidx.fragment.app.Fragment;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fastlib.utils.permission.FastPermission;
import com.fastlib.utils.permission.OnPermissionCallback;
import com.fastlib.utils.permission.Permission;
import com.orhanobut.logger.Logger;
import com.wlbx.agent.R;
import com.wlbx.agent.adapter.vp.VpFragmentAdapter;
import com.wlbx.agent.base.BaseActivity;
import com.wlbx.agent.bean.VersionBean;
import com.wlbx.agent.event.HiddenTabEvent;
import com.wlbx.agent.event.UpdateDrawerLayoutEvent;
import com.wlbx.agent.event.UpdateProductListEvent;
import com.wlbx.agent.global.Constant;
import com.wlbx.agent.net.RequestManager;
import com.wlbx.agent.net.RetrofitCallBack;
import com.wlbx.agent.net.RetrofitRequestInterface;
import com.wlbx.agent.global.AccountManager;
import com.wlbx.agent.ui.fragment.tab.HomeFragment;
import com.wlbx.agent.ui.fragment.tab.MineFragment;
import com.wlbx.agent.ui.fragment.tab.ProductFragment;
import com.wlbx.agent.ui.fragment.tab.ReplayFragment;
import com.wlbx.agent.util.ActivityUtil;
import com.wlbx.agent.util.AppUtil;
import com.wlbx.agent.util.NotificationUtil;
import com.wlbx.agent.util.SPUtil;
import com.wlbx.agent.util.VersionUtil;
import com.wlbx.agent.util.fingerprint.CryptoObjectHelper;
import com.wlbx.agent.util.fingerprint.MyAuthCallback;
import com.wlbx.agent.view.NoScrollViewPager;
import com.wlbx.agent.view.dialog.QueryDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.crypto.KeyGenerator;
import butterknife.BindView;
import okhttp3.Call;

public class MainActivity extends BaseActivity {
    private static final String TAG = "MainActivity";

    @BindView(R.id.vp_activity_main)
    NoScrollViewPager mMainVP;
    @BindView(R.id.rg_activity_main)
    RadioGroup mMainRG;
    private List<Fragment> mFragList = new ArrayList<>();
    private VpFragmentAdapter mAdapter;

    @BindView(R.id.rd_activity_main_mine)
    RadioButton mRBMine;
    @BindView(R.id.rd_activity_main_home)
    RadioButton mRBHome;
    @BindView(R.id.rd_activity_main_product)
    RadioButton mRBProduct;
    @BindView(R.id.rd_activity_main_replay)
    RadioButton mRBReplay;
    private int currentItem = 0;
    //指纹
    private PopupWindow mPopupFingerPrintWindow;
    private Handler mHandler = new Handler();
    private KeyStore mKeyStore;
    private KeyGenerator mKeyGenerator;
    private Handler handler;
    private FingerprintManagerCompat fingerprintManager;
    private MyAuthCallback myAuthCallback;
    private CancellationSignal cancellationSignal;
    public static final int MSG_AUTH_SUCCESS = 100;
    public static final int MSG_AUTH_FAILED = 101;
    public static final int MSG_AUTH_ERROR = 102;
    public static final int MSG_AUTH_HELP = 103;
    public boolean checked = false;

    @Override
    protected void onResume() {
        super.onResume();
        if (!EventBus.getDefault().isRegistered(this))
        {
            EventBus.getDefault().register(this);
        }

        if(getIntent().getExtras()!= null) {
            String to = getIntent().getExtras().getString("to");

            if("0".equals(to)) {
                mMainVP.setCurrentItem(0, false);
                checkedButton(0);
                currentItem = 0;
            }
            if("1".equals(to)) {
                mMainVP.setCurrentItem(1, false);
                checkedButton(1);
                currentItem = 1;
            }
            if("2".equals(to)) {
                mMainVP.setCurrentItem(2, false);
                currentItem = 2;
            }
            if("3".equals(to)) {
                mMainVP.setCurrentItem(3, false);
                currentItem = 3;
            }
            getIntent().removeExtra("to");
        }
    }

    @Override
    public void initData() {
        if(checkLogin()&&Constant.FINGER_PRINT){
            Constant.FINGER_PRINT=false;
            if("1".equals(SPUtil.get("fingerprint","0"))&&!checked) {
                mHandler.postDelayed(mRunnable, 500);
            }else{
                if(Constant.INSTALL_LATER){
                    Constant.INSTALL_LATER=false;
                    getVersionInfo();
                }
            }
        }else{
            if(Constant.INSTALL_LATER){
                Constant.INSTALL_LATER=false;
                getVersionInfo();
            }

        }

        mMainVP.setNoScroll(true);
        mFragList.add(new HomeFragment());
        mFragList.add(new ProductFragment());
        mFragList.add(new ReplayFragment());
        mFragList.add(new MineFragment());

        mAdapter = new VpFragmentAdapter(getSupportFragmentManager(), mFragList);

        mMainVP.setAdapter(mAdapter);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //判断是否需要开启通知栏功能
            NotificationUtil.OpenNotificationSetting(mContext, new NotificationUtil.OnNextLitener() {
                @Override
                public void onNext() {
//                    Toast.makeText(mContext,"已开启通知权限",Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    private void checkApp(String downloadUrl, String forceUpdate) {
        FastPermission.with(this)
                .permissions(Permission.READ_EXTERNAL_STORAGE,Permission.WRITE_EXTERNAL_STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onPermissionSuccess() {
                        downLoadApk(downloadUrl, forceUpdate);
                    }

                    @Override
                    public void onPermissionFailure(String hint) {

                    }
                });
    }


    @Override
    public void initEvent() {
        mMainRG.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rd_activity_main_home:
                        mMainVP.setCurrentItem(0, false);
                        checkedButton(0);
                        currentItem = 0;
                        break;
                    case R.id.rd_activity_main_product:
                        break;
                    case R.id.rd_activity_main_replay:
                        mMainVP.setCurrentItem(2, false);
                        checkedButton(2);
                        currentItem = 2;
                        break;
                    case R.id.rd_activity_main_mine:
                        if (checkLogin()) {
                            mMainVP.setCurrentItem(3, false);
                            checkedButton(3);
                            currentItem = 3;
                        }else{
                            checkedButton(currentItem);
                            startActivity(new Intent(mContext, LoginActivity.class));
                        }
                        break;
                    default:
                        break;
                }

            }
        });
        mRBProduct.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMainVP.setCurrentItem(1, false);
                        checkedButton(1);
                        currentItem = 1;
            }
        });
    }

    /**
     * 跳转到tab2
     */
    public void toTab2(String isOnline) {
        MainActivity mainActivity = (MainActivity) mContext;
        mainActivity.setFragment2Fragment(new MainActivity.Fragment2Fragment() {
            @Override
            public void gotoFragment(NoScrollViewPager viewPager) {
                viewPager.setCurrentItem(1, false);
                checkedButton(1);
                currentItem = 1;
            }
        });
        mainActivity.forSkip();
        UpdateProductListEvent updateProductListEvent = new UpdateProductListEvent();
        updateProductListEvent.setProductName(Constant.PRODUCT_NAME);
        updateProductListEvent.setIsOnline(isOnline);
        EventBus.getDefault().postSticky(updateProductListEvent);
    }

    /**
     * 跳转到首页
     */
    public void toLogin(){
        AccountManager.setUserLogin(false);
        AccountManager.removeSP();
        Intent intent = new Intent(this,LoginActivity.class);
        startActivity(intent);
    }

    public interface Fragment2Fragment{
        void gotoFragment(NoScrollViewPager viewPager);
    }
    private  Fragment2Fragment fragment2Fragment;
    public void setFragment2Fragment(Fragment2Fragment fragment2Fragment){
        this.fragment2Fragment = fragment2Fragment;
    }

    public void forSkip(){
        if(fragment2Fragment!=null){
            fragment2Fragment.gotoFragment(mMainVP);
        }
    }
    private void checkedButton(int currentItem){
        if(currentItem == 0){
            mRBHome.setChecked(true);
        }else if(currentItem == 1){
            mRBProduct.setChecked(true);
        }else if(currentItem == 2){
            mRBReplay.setChecked(true);
        }else if(currentItem == 3){
            mRBMine.setChecked(true);
        }
    }


    @Override
    protected int getContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        ActivityUtil.getInstance().finishAllActivity();
    }

    /**
     * 校验当前用户是否登录
     */
    public boolean checkLogin(){
        if(!"".equals(SPUtil.get("phone",""))){
            return true;
        }else{
            return false;
        }
    }

    
    
    
    

//////////////////////////检查更新apk/////////////////////////////

    private void getVersionInfo() {
        String versionNo= String.valueOf(AppUtil.getAppVersionName(MainActivity.this));
        Logger.i("versionNo---"+versionNo);
        RequestManager
                .mRetrofitManager
                .createRequest(RetrofitRequestInterface.class)
                .getVersionInfo("01",versionNo)
                .enqueue(new RetrofitCallBack() {
                    @Override
                    public void onSuccess(String response) {
                        Logger.i( "版本更新---"+response);
                        JSONObject jsonObject = JSON.parseObject(response);
                        String rCode = jsonObject.getString("code");
                        String rMsg  = jsonObject.getString("msg");
                        if("1000".equals(rCode)) {
                            VersionBean versionBean=JSON.parseObject(response,VersionBean.class);
                            String forceUpdate=versionBean.getData().getIsMandatory();
                            String downUrl=versionBean.getData().getDownloadUrl();
                            try {

                                if (VersionUtil.compareVersion(versionBean.getData().getVersionNo(), AppUtil.getAppVersionName(MainActivity.this)) > 0) {
                                    QueryDialog mQueryDialog = new QueryDialog(MainActivity.this,versionBean.getData().getVersionNo(),"",forceUpdate, new QueryDialog.DialogGoback() {
                                        @Override
                                        public void query() {

                                            updateApk(downUrl, forceUpdate);
                                        }
                                    });
                                    mQueryDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
                                    //Y.强制更新；N.非强制更新
                                    if ("Y".equals(forceUpdate)) {
                                        mQueryDialog.setCanceledOnTouchOutside(false);
                                        mQueryDialog.setCancelable(false);
                                        mQueryDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                                            @Override
                                            public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
                                                return false;
                                            }
                                        });
                                    }
                                    mQueryDialog.show();

                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }else{
                            Toast.makeText(MainActivity.this,rMsg,Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        Logger.i( t.getMessage());

                    }
                });
    }



    private void updateApk(String downloadUrl, String forceUpdate) {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            checkApp(downloadUrl, forceUpdate);


        } else {
            Toast.makeText(MainActivity.this, "SD卡不可用，请插入SD卡", Toast.LENGTH_LONG).show();
        }
    }
    ProgressDialog progressDialog;

    private void downLoadApk(String downloadUrl, final String forceUpdate) {
        //进度条，在下载的时候实时更新进度，提高用户友好度
        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setTitle("正在下载");
        progressDialog.setMessage("请稍候...");
        progressDialog.setProgress(0);
        progressDialog.show();

        OkHttpUtils.get().url(downloadUrl).build()
                .execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(), "wlbx.apk") {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Logger.i(TAG, "onError :" + e.getMessage());

                    }

                    @Override
                    public void onResponse(final File file, int id) {
                        Logger.i(TAG, "onResponse :" + file.getAbsolutePath());
                        installApk(file.getAbsolutePath(), forceUpdate);
                    }

                    @Override
                    public void inProgress(float progress, long total, int id) {
                        super.inProgress(progress, total, id);
                        Logger.i(TAG, (int) (100 * progress) + "%");
                        downLoading((int) (100 * progress));
                    }
                });
    }

    private void installApk(final String filePath, final String forceUpdate) {

        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }

        new AlertDialog.Builder(MainActivity.this).setTitle("下载完成").setCancelable(false)
                .setMessage("是否安装")
                .setPositiveButton(
                        "是",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {



                                File file = new File(filePath);

//更新包文件
                                Intent intent = new Intent();

                                intent.setAction(Intent.ACTION_VIEW);

                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)

                                { // Android7.0及以上版本 Log.d("-->最新apk下载完毕","Android N及以上版本");

                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

                                    intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

                                    Uri contentUri = FileProvider.getUriForFile(MainActivity.this, "com.wlbx.agent.fileprovider", file);

//参数二:应用包名+".fileProvider"(和步骤二中的Manifest文件中的provider节点下的authorities对应)

                                    intent.setDataAndType(contentUri, "application/vnd.android.package-archive");

                                } else {

// Android7.0以下版本 Log.d("-->最新apk下载完毕","Android N以下版本");

                                    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");

                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                }

                                startActivity(intent);


                            }
                        }
                ).setNegativeButton(
                R.string.cancel, new DialogInterface.OnClickListener() {
                    //添加返回按钮
                    @Override
                    public void onClick(DialogInterface dialog, int which) {//响应事件

                    }

                }
        ).show();//在按键响应事件中显示此对话框


    }


    /**
     * 进度条实时更新
     *
     * @param i
     */
    public void downLoading(final int i) {
        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progressDialog.setProgress(i);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void hiddenTab(HiddenTabEvent hiddenTabEvent) {
    if (hiddenTabEvent.isHidden()){
        mMainRG.setVisibility(View.GONE);
    }else {
        mMainRG.setVisibility(View.VISIBLE);
    }
    }



    /**
     * 双击退出函数
     */
    private static Boolean isExit = false;

    private void exitBy2Click() {
        Timer tExit = null;
        if (isExit == false) {
            isExit = true; // 准备退出
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务

        } else {
            ActivityUtil.getInstance().finishAllActivity();
            System.exit(0);
        }

    }
    //拦截返回事件
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            if(currentItem == 2){
                ((ReplayFragment)mFragList.get(2)).backPre();
            }else {
                exitBy2Click();
            }
            return  true;
        } else if (keyCode == KeyEvent.KEYCODE_MENU) {// MENU键
            // 监控/拦截菜单键
            return true;
        }
       return super.onKeyDown(keyCode, event);
    }

    private void initFingerPrint(){
        //读取指纹设置
        String flag = (String)SPUtil.get("fingerprint","0");
        if("1".equals(flag)){
            if (mPopupFingerPrintWindow != null && mPopupFingerPrintWindow.isShowing()) {
                mPopupFingerPrintWindow.dismiss();
            } else {
                View view = mInflater.inflate(R.layout.pop_fingerprint_login, null);
                mPopupFingerPrintWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                mPopupFingerPrintWindow.showAtLocation(view, Gravity.NO_GRAVITY, 0, 0);
            }
        }
    }

    private void initFingure() {
        fingerprintManager = FingerprintManagerCompat.from(this);
        if (!fingerprintManager.isHardwareDetected()) {
            Toast.makeText(mContext,"您的设备上没有指纹传感器，点击取消退出",Toast.LENGTH_SHORT).show();
        } else if (!fingerprintManager.hasEnrolledFingerprints()) {
            Toast.makeText(mContext,"没有指纹登记，请到设置->安全中设置",Toast.LENGTH_SHORT).show();
        } else {
            try {
                String flag = (String)SPUtil.get("fingerprint","0");
                if("1".equals(flag)) {
                    setFingurePws();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }



    private void setFingurePws() {
        // TODO Auto-generated method stub
        try {
            mKeyStore = KeyStore.getInstance("AndroidKeyStroe");
        } catch (KeyStoreException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            mKeyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStroe");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        }

        initFingerPrint();

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                Logger.d(TAG, "onError :" + msg.what);
                switch (msg.what) {
                    case MSG_AUTH_SUCCESS:
                        setResultInfo("SUCCESS");
                        cancellationSignal = null;
                        break;
                    case MSG_AUTH_FAILED:
                        setResultInfo("指纹识别失败");
                        cancellationSignal = null;
                        break;
                    case MSG_AUTH_ERROR:
                        handleErrorCode(msg.arg1);
                        break;
                    case MSG_AUTH_HELP:
                        handleHelpCode(msg.arg1);
                        break;
                }
            }
        };
        myAuthCallback = new MyAuthCallback(handler);
        try {
            CryptoObjectHelper cryptoObjectHelper = new CryptoObjectHelper();
            if (cancellationSignal == null) {

                cancellationSignal = new CancellationSignal();
            }
            fingerprintManager.authenticate(cryptoObjectHelper.buildCryptoObject(),0, cancellationSignal, myAuthCallback, null);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(MainActivity.this, "指纹识别初始化失败，请重试！", Toast.LENGTH_SHORT).show();
        }
    }

    private void handleErrorCode(int code) {
        Logger.d(TAG, "onError :" + code);
        switch (code) {
            case FingerprintManager.FINGERPRINT_ERROR_USER_CANCELED:
            case FingerprintManager.FINGERPRINT_ERROR_CANCELED:
                mPopupFingerPrintWindow.dismiss();
                ActivityUtil.getInstance().finishAllActivity();
                System.exit(0);
                break;
            case FingerprintManager.FINGERPRINT_ERROR_HW_UNAVAILABLE:
                setResultInfo("硬件不可用，请稍后再试");
                break;
            case FingerprintManager.FINGERPRINT_ERROR_LOCKOUT:
                setResultInfo("LOCKED");
                break;
            case FingerprintManager.FINGERPRINT_ERROR_NO_SPACE:
                setResultInfo("无法完成操作，因为还没有足够的存储空间来完成操作");
                break;
            case FingerprintManager.FINGERPRINT_ERROR_TIMEOUT:
                setResultInfo("操作超时，请重试");
                break;
            case FingerprintManager.FINGERPRINT_ERROR_UNABLE_TO_PROCESS:
                setResultInfo("指纹图像无法识别，请重试");
                break;
        }
    }

    private void setResultInfo(String stringId) {
        if ("SUCCESS".equals(stringId)) {
            Toast.makeText(MainActivity.this, "已解锁", Toast.LENGTH_SHORT).show();
            mPopupFingerPrintWindow.dismiss();
            checked = true;
            if ( Constant.INSTALL_LATER) {
                Constant.INSTALL_LATER=false;
                getVersionInfo();
            }
        }else if("LOCKED".equals(stringId)){
            Toast.makeText(getApplicationContext(), "识别错误次数太多,请重新登录", Toast.LENGTH_SHORT).show();
            if(cancellationSignal!=null){
                cancellationSignal.cancel();
                cancellationSignal = null;
            }
            mPopupFingerPrintWindow.dismiss();
            toLogin();

        }else{
            Toast.makeText(MainActivity.this, stringId, Toast.LENGTH_SHORT).show();
        }


    }


    private void handleHelpCode(int code) {
        switch (code) {
            case FingerprintManager.FINGERPRINT_ACQUIRED_GOOD:
                setResultInfo("获得的图像是好的");
                break;
            case FingerprintManager.FINGERPRINT_ACQUIRED_IMAGER_DIRTY:
                setResultInfo("由于传感器上的可疑或检测到的灰尘，指纹图像太嘈杂了。");
                break;
            case FingerprintManager.FINGERPRINT_ACQUIRED_INSUFFICIENT:
                setResultInfo("指纹图像太嘈杂了");
                break;
            case FingerprintManager.FINGERPRINT_ACQUIRED_PARTIAL:
                setResultInfo("请紧按指纹传感器");
                break;
            case FingerprintManager.FINGERPRINT_ACQUIRED_TOO_FAST:
                setResultInfo("手指移动过快");
                break;
            case FingerprintManager.FINGERPRINT_ACQUIRED_TOO_SLOW:
                setResultInfo("请移动手指");
                break;
        }
    }

    private Runnable mRunnable = new Runnable() {
        public void run() {
            initFingure();
        }
    };


}
